<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>食物管理</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <div id="app">

    <!-- 新增表单 -->
    <h2>新增食物</h2>
    <form @submit.prevent="addFood">
       <div>
         <label>名称：</label>
        <input v-model="food.name" placeholder="请输入食物名称" required />
      </div>
       <div>
         <label>类型：</label>
        <input v-model="food.type" placeholder="请输入食物类型" required />
      </div>
       <div>
         <label>评分：</label>
        <input v-model="food.score" placeholder="请输入食物评分" required />
      </div>
       <div>
         <label>说明：</label>
        <input v-model="food.info" placeholder="请输入食物说明信息" required>
      </div>
      <button type="submit">提交</button>
    </form>
    <h2>食物列表</h2>

    <!-- 食物列表 -->
    <ul>
      <li v-for="item in foods" :key="item.id">
        {{ item.name }} - {{ item.ctime }}
      </li>
    </ul>

  </div>

  <script>
    const { createApp } = Vue;

    createApp({
      data() {
        return {
          foods: [],             // 存储食物列表
          food: {
            name: '',
            type: '',
            score: '',
            info: ''
          },
        };
      },
      methods: {
        // 获取所有食物
        async fetchFoods() {
          try {
            const res = await axios.get('/food/all');
            this.foods = res.data;
          } catch (err) {
            alert('获取数据失败');
            console.error(err);
          }
        },
        // 提交新增食物
        async addFood() {
          try {
            await axios.post('/food/save',this.food);

            this.fetchFoods(); // 刷新列表
          } catch (err) {
            alert('新增失败');
            console.error(err);
          }
        }
      },
      mounted() {
        this.fetchFoods(); // 页面加载时获取数据
      }
    }).mount('#app');
  </script>
</body>
</html>

</body>
</html>